from bokeh.palettes import Spectral5
from bokeh.sampledata.autompg import autompg as df
from bokeh.transform import factor_cmap
from bokeh.sampledata.autompg import autompg_clean as df
from bokeh.plotting import figure
from pyecharts import options as opts
from pyecharts.charts import Map
import pandas as pd


def mpg():
    '''bokeh绘制柱状图 自我实践案例2'''
    df.cyl = df.cyl.astype(str)
    group = df.groupby(['cyl', 'mfr'])
    index_cmap = factor_cmap('cyl_mfr', palette=Spectral5, factors=sorted(df.cyl.unique()), end=1)
    
    p = figure(plot_width=1000, plot_height=800, title="Mean MPG by # Cylinders and Manufacturer",
           x_range=group, tooltips=[("MPG", "@mpg_mean"), ("Cyl, Mfr", "@cyl_mfr")])
    
    p.vbar(x='cyl_mfr', top='mpg_mean', width=1, source=group,
       line_color="white", fill_color=index_cmap, )
    
    p.y_range.start = 0
    p.x_range.range_padding = 0.05  
    p.xgrid.grid_line_color = None
    p.xaxis.axis_label = "Manufacturer grouped by # Cylinders"
    p.xaxis.major_label_orientation = 1.2
    p.outline_line_color = None
    
    return p

def vbar_demo():
    '''bokeh绘制柱状图 案例1'''
    fig = figure(plot_width=300, plot_height=300)
    fig.vbar(
        x=[1, 2, 3, 4],
        width=0.5,
        bottom=0,
        top=[1.7, 2.2, 4.6, 3.9],
        color='navy'
    )
    
    return fig

def totalmap():
    '''总人口地图'''
    total = pd.read_csv('china_provinces_population.csv')
    pro = total['省']
    num = total['人口数']
    data = [list(z) for z in zip(pro, num)]
    c = (
        Map()
            .add("人数", data, "china")
            .set_global_opts(
            title_opts=opts.TitleOpts(title="Map-人数分布"),
            visualmap_opts=opts.VisualMapOpts(
                max_=100000000,
                is_piecewise=True
            ),
            legend_opts=opts.LegendOpts(
                pos_left=20,
                pos_top=100,
            ),
            toolbox_opts=opts.ToolboxOpts(
                pos_right=20,
                pos_top=20,
            )
        )
    )
    return render_template(totalmap.html)

def totalnummap():
    '''总人口'''
    pwork['劳动力占比'] = pwork['劳动力(万人)']/pwork['年末总人口(万人)']
    x = pwork['指标']
    y1 = pwork['年末总人口(万人)']
    # 绘制折线图
    c = (
        Line()
        .add_xaxis(xaxis_data=x)
        .add_yaxis(
            series_name="全国总人口",
            stack="总量",
            y_axis=y1,
            label_opts=opts.LabelOpts(is_show=False),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="中国总人口历史变化"),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
        )
    )
    return c.render_notebook()
